package cn.edu.ncu.housinghub.service.impl;

import cn.edu.ncu.housinghub.constant.ErrorCodeConstant;
import cn.edu.ncu.housinghub.constant.SystemConstant;
import cn.edu.ncu.housinghub.dto.request.agent.ApplyAgentHouse;
import cn.edu.ncu.housinghub.entity.house.House;
import cn.edu.ncu.housinghub.entity.user.Agent;
import cn.edu.ncu.housinghub.entity.user.User;
import cn.edu.ncu.housinghub.exception.BusinessException;
import cn.edu.ncu.housinghub.mapper.HouseMapper;
import cn.edu.ncu.housinghub.mapper.UserMapper;
import cn.edu.ncu.housinghub.service.AgentRentalService;
import cn.edu.ncu.housinghub.service.UserService;
import cn.edu.ncu.housinghub.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AgentRentalServiceImpl implements AgentRentalService {
    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<House> getAllAgentRentalHouse() {
        // 获取所有可代理的房源（出租类型为中介代理且未被代理的房源）
        try {
            return houseMapper.selectAvailableAgentHouses();
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "获取可代理房源失败");
        }
    }

    @Override
    public List<House> getAllAgentHouse(Long userId) {
        // 获取某个中介代理的所有房源
        try {
            Agent agent = getAgentInfoByUserId(userId);
            return houseMapper.selectAllAgentHouseByAgentId(agent.getAgentId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "获取代理房源失败");
        }
    }

    @Override
    public List<House> getAllAgentingHouse(Long userId) {
        // 获取某个中介正在代理的房源（状态为待出租）
        try {
            Agent agent = getAgentInfoByUserId(userId);
            return houseMapper.selectAgentingHouseByAgentId(agent.getAgentId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "获取正在代理房源失败");
        }
    }

    @Override
    public List<House> getAllAgentRentedHouse(Long userId) {
        // 获取某个中介已经出租的房源（状态为已出租）
        try {
            Agent agent = getAgentInfoByUserId(userId);
            return houseMapper.selectRentedHouseByAgentId(agent.getAgentId());
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "获取已出租房源失败");
        }
    }

    @Override
    public Agent getAgentInfoByUserId(Long userId) {
        Agent agent = userMapper.selectAgentByUserId(userId);
        if (agent == null) {
            throw new BusinessException(ErrorCodeConstant.Agent_INFO_NOT_MATCH);
        }
        return agent;
    }

    @Override
    public Result applyAgentHouse(Long userId, ApplyAgentHouse applyAgentHouse) {
        try {
            // 验证中介信息
            Agent agent = getAgentInfoByUserId(userId);

            // 验证房源信息
            House house = houseMapper.selectHouseByHouseId(applyAgentHouse.getHouseId());
            if (house == null) {
                throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_FOUND);
            }

            // 检查房源是否已被代理
            if (house.getAgent() != null && house.getAgent().getAgentId() != null) {
                throw new BusinessException(ErrorCodeConstant.HOUSE_ALREADY_AGENT);
            }

            // 检查房源类型是否支持中介代理
            if (house.getHouseRentType() != SystemConstant.HOUSE_RENT_TYPE_AGENT.getIntegerValue()) {
                throw new BusinessException(ErrorCodeConstant.HOUSE_NOT_SUPPORT_AGENT);
            }

            // 创建代理申请记录
            houseMapper.insertAgentHouseApplication(agent.getAgentId(), applyAgentHouse.getHouseId(),
                applyAgentHouse.getReason());

            return Result.success("代理申请提交成功，等待房东审核");
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException(ErrorCodeConstant.SYSTEM_ERROR, "申请代理失败：" + e.getMessage());
        }
    }
}
